<?php
/***user auth***/

class UserAuth{
	private $db;							//数据库连接
	private $main_table='data_user';			//用户表
	private $usecookie='0';					//是否用cookie
	private $key='userkey';					//cookie字段名

	
	public function __construct($db){
		$this->db=$db;
	}

	public function __destruct(){
		unset($this->db);
	}
	public function get_table_name(){
	    return $this->main_table;
	    
	}
	
	//登录验证
	private function check_pwd($username,$pwd){		
		//$this->db->setDebug(1,1);		
		$where = "user_name='".inputSQL($username)."' AND user_pwd='".md5($pwd)."'";
		$sql="SELECT  user_id,user_name,user_status,user_email,user_last_login,user_phone,user_close_reason,user_headimg,user_truename FROM ".$this->main_table." WHERE ".$where;
		$row=$this->db->getRow($sql);
		//$row = array("user_id"=>'10',"user_name"=>$username,"user_status"=>'1','time'=>date("Y-m-d H:i:s"));
		return $row;
	}

/*	public function go_login($row){
		$_SESSION['user_auth'] = array(1,2);
		my_print($_SESSION['user_auth']);
		return false;
	}*/
	
	//获取登录信息
	private function get_login_info($row,$cookie=''){
		if(is_array($row)){
			$this->db->update($this->main_table,array("user_last_login"=>date("Y-m-d H:i:s"),"user_login_count"=>"user_login_count+1"),"user_id='".$row['user_id']."'");
			
			if($this->usecookie){
				$row['login']= intval($cookie);										//用cookie 自动登录
				$this->set_user_cookie($row);
			}else{
				
				$_SESSION['user_auth'] = $row;
			}
			//my_print($_SESSION['user_auth']);
			return $row;
		}else{
			return false;
		}

	}

	//登录操作
	public function login($username,$pwd,$cookie='0'){
		$row = $this->check_pwd($username,$pwd);		
		return $this->get_login_info($row,$cookie);

	}
	
	
	//判断是否登录中
	public function check_login(){
		$userinfo = $this->get_user_info();
		//dump($userinfo);
		if($userinfo['user_id'] && $userinfo['user_name'] && $userinfo['user_status']=='1'  ){
			return $userinfo;	
		}else{
			$this->clean_user_cookie();
			return false;	
		}
	}

	//获取用户信息
	public function get_user_info(){
		
		if($this->usecookie){
				$row = $this->get_user_cookie();
			}else{
				
				$row = $_SESSION['user_auth'] ;
		}
		
		return $row;
	}

	//退出登录
	public function logout(){
		$userinfo = $this->get_user_info();
		$this->db->update($this->main_table,array("user_last_logout"=>time()),"user_id='".$userinfo['user_id']."'");
		
		if($this->usecookie){
				$this->clean_user_cookie();
			}else{
				
				unset($_SESSION['user_auth']);
				
		}
	}

	
/*	public function check_active(){
		$userinfo = $this->get_user_info();
		if($userinfo['user_check']=='0'){
			$more = '<a class="blue" href="'.SITE_ADDR.'user/user.htm">进入会员中心,进行激活</a>&nbsp;&nbsp;<a href="javascript:history.back()">返回</a>';
			my_jump('您的账号还没进行激活,请激活后再操作!  '.$more,'',$cf_self_path.'-act_index_rid_'.$rid.'.htm');
		}
	}*/


	/**
	* 	check user
	* 	@param array $data 
	* 	@param string $where 
	* 	@return int affected count
	*/
	public function check_user($name){		
		$where = "user_name='".inputSQL($name)."'";
		$sql="SELECT user_id,user_name,user_phone FROM ".$this->main_table." WHERE ".$where;
		$row=$this->db->getRow($sql);
		return $row;
	}
	
	
	/**
	* 	update user
	* 	@param array $data 
	* 	@param string $where 
	* 	@return int affected count
	*/
	public function update_data($data,$where){
		if(!is_array($data))
		my_jump('输入的参数有误');
		$result = $this->db->update($this->main_table,$data,$where);
		return $result;
	}

	private function set_user_cookie($row){
		if(is_array($row)){
			load_file('crypt_class', LIB_PATH);
			$crypt = new Crypt(API_KEY);
			$value = $crypt->myencrypt($row);
			$domain =get_domain();
			setcookie($this->key,$value,time()+COOKIE_EXPIRE,"/",$domain);
			return $row;
		}else{
			return false;	
		}
		
	}
	private function get_user_cookie(){
		$value = $_COOKIE[$this->key];	
		if($value){
			load_file('crypt_class', LIB_PATH);
			$crypt = new Crypt(API_KEY);
			$row = $crypt->mydecrypt($value);	
			if(is_array($row)){
				$this->set_user_cookie($row);				//延长cookie
				return $row;	
			}
		}else{
			return false;	
			
		}
		
	}
	
	private function clean_user_cookie(){
		$domain =get_domain();
		setcookie($this->key,"",time()-3600,"/",$domain);
	}
	
	//QQ号登录
	public function qq_login($openid,$row){		
		//判断openid是否注册
		$sql = "SELECT user_id,user_name,user_status,user_email,user_last_login,user_phone,user_close_reason,user_headimg,user_truename FROM ".$this->main_table." WHERE user_qq_openid ='".$openid."'";
		$info = $this->db->getRow($sql);
		load_file('user_class', LIB_PATH);
		$main = new User($this->db);				
		if($info){//如果已经注册，则对比信息更新头像和昵称进行
			if($info['user_nickname'] != $row['nickname'] || $info['user_headimg'] != $row['figureurl_qq_1']){
				$update['user_nickname'] = $row['nickname'];
				$update['user_headimg'] = $row['figureurl_qq_1'];
				$main->update_data($update,"user_id = '".$info['user_id']."'");
				$info['user_nickname'] = $row['nickname'];
				$info['user_headimg'] = $row['figureurl_qq_1'];				
			}			
			$this->get_login_info($info);			//登录session
			return true;				
			
		}else{//如果已经注册，则注册并登陆
			$max = $main->get_max_id();
			$data = array(
						'user_id' => $max,
						'user_qq_openid' => $openid,
						'user_pwd' => '',
						'user_name' => 'qq'.$max,
						'user_nickname' => $row['nickname'],
						'user_headimg' => $row['figureurl_qq_1'],											
						'user_reg_time' => date("Y-m-d H:i:s"),
						'user_reg_ip' => get_ip(),
						'user_status' => '1',						
						'user_from' => '1'
					);			
			$user_id = $main->insert_data($data);								
			if($user_id){
				$info['user_id'] = $max;
				$info['user_nick_name'] = $row['nickname'];
				$info['user_headimg'] = $row['figureurl_qq_1'];
				$info['user_status'] = '1';						
				$this->get_login_info($info);
				return true;
			}else{				
				return false;
			}			
		}		
       
	}
	
	//sina 登录
	public function sina_login($row){
		$userinfo = $this->check_api_user('3',$row['id'],$row);
		if($userinfo){
			$this->get_login_info($userinfo);			//登录session
			return true;
		}else{
			return false;
		}
		//来源资源
		//1 注册用户
		//2 生成session	
	}
	
	//判断用户是否存在,不存在则添加
	public function check_api_user($type,$id,$row){
		switch($type){
				case "qq":
				$main_id = "user_api_qq_openid";
				break;
				case "sina":
				$main_id = "user_api_sina_id";
				break;
				case "wx":
				$main_id = "user_api_wx_openid";
				break;
				default:
				$main_id = "user_api_sina_id";
				break;
				
		}
        //echo $this->db->debug(1,1);
		$sql="SELECT * FROM ".$this->main_table." WHERE ".$main_id."='".$id."' ";
		$info=$this->db->getRow($sql);
		if($info){
			return $info;	
		}else{
			load_file('user_class', LIB_PATH);
			$main = new User($db);						
			$max = $main->get_max_id();
			switch($type){
				case "sina":				//新浪微博
					$data = array(
						'user_id' => $max,
						'user_pwd' => 'empty',
						'user_name' => 'sina'.$max,
						'user_photo' => trim($row['profile_image_url']),
						'user_nick_name' => trim($row['screen_name']),
						'user_addr' => trim($row['location']),
						'user_reg_from' => '3',
						'user_api_sina_page' => 'http://weibo.com/'.trim($row['profile_url']),
						'user_api_sina_id' => $row['id'],
						'user_score' => '100',
						'user_reg_time' => date("Y-m-d H:i:s"),
						'user_reg_ip' => get_ip(),
						'user_channel_sn' => trim($row['channel_sn']),
						'user_phone_imei' => trim($row['imei']),
						'user_status' => '1'

					);	
				break;
				case "qq":				//QQ
					$data = array(
						'user_id' => $max,
						'user_pwd' => '',
						'user_name' => 'qq'.$max,
						'user_nick_name' => $row['nickname'],
						'user_headimg' => $row['figureurl_qq_1'],					
						'user_reg_from' => '2',
						'user_api_qq_openid' => $id,						
						'user_reg_time' => date("Y-m-d H:i:s"),
						'user_reg_ip' => get_ip(),
						'user_status' => '1'
					);	
				break;	
			}
			
			//插入注册信息
            //$this->db->debug(1,1);
			$user_id = $main->insert_data($data);
					
			if ($user_id) {					
				$sql="SELECT * FROM ".$this->main_table." WHERE user_id='".$max."' ";
				$info=$this->db->getRow($sql);
				return $info;
			}else{				
				return false;
			}
		

		}
	}
	
	
}



?>